package com.galen.manual.security;

import com.galen.manual.entity.User;
import com.galen.manual.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * 自定义用户详情服务
 * 从数据库中加载用户信息用于Spring Security认证
 */
@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String identifier) throws UsernameNotFoundException {
        User user;

        // 判断是用户名还是手机号
        if (identifier.matches("\\d+")) {
            // 纯数字，按手机号查询
            user = userMapper.selectByPhone(identifier);
        } else {
            // 字符串，按用户名查询
            user = userMapper.selectByUsername(identifier);
        }

        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + identifier);
        }

        // 构建Spring Security的UserDetails对象
        return org.springframework.security.core.userdetails.User.builder()
                .username(identifier) // 使用标识符作为用户名
                .password("") // 密码字段，这里可以填空，因为我们已经通过JWT验证了
                .authorities(Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")))
                .accountExpired(false)
                .accountLocked(false)
                .credentialsExpired(false)
                .disabled(user.getStatus() != 1)
                .build();
    }
}